var express = require('express');
var router = express.Router();
var { LoginModel } = require('../model/model')
var jwt = require("jsonwebtoken");


// 验证身份令牌，实现无感刷新Token
const verifyAuthToken = (req, res, next) => {
  const accessToken = req.headers["authorization"];
  const refreshToken = req.headers["pass"];
  if (!accessToken) {
    return res.status(400).json({ msg: "身份令牌未提供！" });
  }
  jwt.verify(accessToken, "accessToken", (err, decoded) => {
    if (err) {
      if (err.name === "TokenExpiredError") {
        jwt.verify(refreshToken, "refreshToken", (err, decoded) => {
          if (err) {
            return res
              .status(403)
              .json({ msg: "refreshToken过期，请重新登录" });
          }
          let id = decoded.id;
          let newAccessToken = jwt.sign({ id }, "accessToken", {
            expiresIn: "6h",
          });
          let newRefreshToken = jwt.sign({ id }, "refreshToken", {
            expiresIn: "5d",
          });
          return res.status(401).json({
            accessToken: newAccessToken,
            refreshToken: newRefreshToken,
            msg: "新的令牌",
          });
        });
      }
      return res.status(400).json({ msg: "身份验证失败" });
    } else {
      req.user = decoded;
      next();
    }
  });
};

// 登录
router.get('/login', async (req, res) => {
  let user = req.query
  let users = await LoginModel.find({ username: user.username })
  if (users.length > 0) {
    if (users[0].password == user.passwodr) {
      let accessToken = jwt.sign({ id }, "accessToken", { expiresIn: "5s" });
      let refreshToken = jwt.sign({ id }, "refreshToken", { expiresIn: "15s" });
      res.send({
        code: 200,
        msg: '登陆成功',
        accessToken,
        refreshToken,
      })
    } else {
      res.send({
        code: 400,
        msg: '密码错误',
      })
    }
  } else {
    res.send({
      code: 400,
      msg: '用户不存在',
    })
  }
})

// 微信登录
router.get('/wechat', async (req, res) => {
  console.log('这是微信登录');
  res.send({
    code : 200,
    msg : '微信登录成功'
  })
})

// 测试是否连接成功
router.post('/test', async (req, res) => {
  console.log(req.body);
  console.log('111');
  res.send({
    code: 200,
    msg: '连接成功'
  })
})


module.exports = router;
